package com.dc.ai.security.service;

import com.dc.ai.common.result.ResultCode;
import com.dc.ai.entity.dto.UserAuthInfo;
import com.dc.ai.security.model.SysUserDetails;
import com.dc.ai.service.SysUserService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class SysUserDetailsService implements UserDetailsService {

    @Lazy
    @Resource
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserAuthInfo userAuthInfo = sysUserService.getUserAuthInfo(username);
        //用户不存在
        if (userAuthInfo == null) {
            throw new UsernameNotFoundException(username);
        }
        //用户被禁用
        if (userAuthInfo.getStatus() != 1){
            throw new DisabledException(ResultCode.USER_ACCOUNT_LOCKED.getMsg());
        }
        return new SysUserDetails(userAuthInfo);
    }
}
